package de.koller.worlders.engine.tiles.data;

public class TileBuffer {
	private final TileHolder holder;
	
	private TileArray current;
	private TileArray second;

	public TileBuffer( int bw, int bh, TileHolder holder ) {
		this.holder = holder;
		this.current = new TileArray( bw, bh );
		this.second = new TileArray( bw, bh );
	}
	
	public void swapBuffer( int bx, int by ) {
		TileArray tmp = second;
		second = current;
		current = tmp;
		
		current.bx = bx;
		current.by = by;
		for( int x = bx; x < bx+current.tiles.length; x++ )
			for( int y = by; y < by+current.tiles[0].length; y++ ) {
				TileWrap t = second.getTile( x, y );
				if( t == null || !t.getTile().isValid() )
					t = holder.getTile( x, y );
				t.setLastUse();
				current.setTile( x, y, t );
			}	
	}
	
	public TileWrap getTile( int tx, int ty ) {
		return current.getTile( tx, ty );
	}
	
	private static class TileArray {
		private int bx, by;
		private final TileWrap[][] tiles;

		private TileArray( int bw, int bh ) {
			tiles = new TileWrap[ bw ][ bh ];
		}
		
		public void setTile( int tx, int ty, TileWrap t ) {
			if( !isInBounds( tx, ty ) )
				return;
			
			tiles[ tx-bx ][ ty-by ] = t;
		}
		
		public TileWrap getTile( int tx, int ty ) {
			if( !isInBounds( tx, ty ) )
				return null;
			
			return tiles[ tx-bx ][ ty-by ];
		}
		
		public boolean isInBounds( int tx, int ty ) {
			return !( tx < bx || ty < by || tx >= tiles.length + bx || ty >= tiles[0].length + by );
		}
		
	}
	
}
